package com.whf.android.jar.util.x509;

import android.annotation.SuppressLint;

import androidx.annotation.NonNull;

import com.whf.android.jar.app.Latte;

import java.security.SecureRandom;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;


/**
 * HTTPS请求的SSL证书
 *
 * @author qf
 * @version 1.0.1
 */
public final class SSLConfigUtils {

    //获取TrustManager
    @NonNull
    private static TrustManager[] getTrustManager() {
        //就是把下面这个X509TrustManager更换一下
        return new TrustManager[]{new MyX509TrustManager()};
    }

    public static SSLSocketFactory sslSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @NonNull
    public static HostnameVerifier hostnameVerifier() {
        return new HostnameVerifier() {
            @SuppressLint("BadHostnameVerifier")
            public boolean verify(String hostname, SSLSession session) {
                //使用 HTTPS 协议时必须对服务器主机名进行校验，校验失败时应进行正确处理。
                if (Latte.getHostname().equals(hostname) || !Latte.isTrustCertificate()) {
                    return true;
                } else {
                    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                    return hv.verify(hostname, session);
                }
            }
        };
    }


}
